
//
// Created by Nasa on 2024/4/21.
//

#include <iostream>
#include <vector>

using namespace std;
struct Node
{
    int v;
    Node *next;
};

//建立链表
Node *build(vector<int> v)
{
    Node *h = new Node();
    Node *p = h;
    for (int i : v)
    {
        p->next = new Node();
        p->next->v = i;
        p = p->next;
    }
    return h;
}

//打印链表
void printLinkedList(Node *h)
{
    Node *p = h->next;
    while (p)
    {
        cout << p->v << ' ';
        p = p->next;
    }
    cout << endl;
}

// 查找第一个为n的结点的位置(从0开始), 如果没找到返回-1
int findLinkedList(Node *h, int n)
{
    Node *p = h->next;
    int i = 0;
    while (p)
    {
        if (p->v == n)
        {
            return i;
        }
        p = p->next;
        ++i;
    }
    return -1;
}

// 在第n个节点后插入值为x的结点,如果成功返回1,失败返回0
int insertLinkedList(Node *h, int n, int x)
{
    Node *cur = h->next;
    int i = 0;
    Node *p=new Node{x, nullptr};
    while (cur)
    {
        if (i==n)
        {
            p->next=cur->next;
            cur->next=p;
            return 1;
        }
        cur = cur->next;
        ++i;
    }
    return 0;
}

int main()
{
    vector<int> l = {5, 4, 3, 2, 1, 0};
    Node *head = build(l);
    printLinkedList(head);
    cout << findLinkedList(head,20)<<endl;
    cout << insertLinkedList(head,2,9)<<endl;
    printLinkedList(head);
    return 0;
}